/// 设置页面
part of pda.page;

class PageDownload extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _PageDownloadState();
  }
}

class _PageDownloadState extends State<PageDownload> {
  final TextStyle buttonTextStyle = TextStyle(fontSize: 16);
  bool busy = false;
  String loadingText = '';
  Size screenSize;
  static var batch;

  @override
  void initState() {
    batch = SqliteHelper.instance.batch;
    super.initState();
  }

  @override
  void didUpdateWidget(PageDownload oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    if (screenSize == null) {
      screenSize = MediaQuery.of(context).size;
    }
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: () {
                if (busy) {
                  return;
                }
                Navigator.of(context).pop();
              }),
          title: Text('下载'),
        ),
        body: Stack(
          children: <Widget>[
            ListView(
              padding: EdgeInsets.symmetric(vertical: 8),
              children: <Widget>[
                ListTile(
                  title: Container(
                    padding: EdgeInsets.symmetric(vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.blue,
                      borderRadius: BorderRadius.all(Radius.circular(4)),
                    ),
                    child: FlatButton(
                      onPressed: downloadUser,
                      textColor: Colors.white,
                      child: Text(
                        '下载用户信息',
                        style: buttonTextStyle,
                      ),
                    ),
                  ),
                ),
                ListTile(
                  title: Container(
                    padding: EdgeInsets.symmetric(vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.blue,
                      borderRadius: BorderRadius.all(Radius.circular(4)),
                    ),
                    child: FlatButton(
                      color: Colors.blue,
                      onPressed: downloadProvider,
                      textColor: Colors.white,
                      child: Text(
                        '下载供应商信息',
                        style: buttonTextStyle,
                      ),
                    ),
                  ),
                ),
                ListTile(
                  title: Container(
                    padding: EdgeInsets.symmetric(vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.blue,
                      borderRadius: BorderRadius.all(Radius.circular(4)),
                    ),
                    child: FlatButton(
                      color: Colors.blue,
                      onPressed: downloadDepart,
                      textColor: Colors.white,
                      child: Text(
                        '下载部门/仓库信息',
                        style: buttonTextStyle,
                      ),
                    ),
                  ),
                ),
                ListTile(
                  title: Container(
                    padding: EdgeInsets.symmetric(vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.blue,
                      borderRadius: BorderRadius.all(Radius.circular(4)),
                    ),
                    child: FlatButton(
                      color: Colors.blue,
                      onPressed: downloadProduct,
                      textColor: Colors.white,
                      child: Text(
                        '下载商品信息',
                        style: buttonTextStyle,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            buildLoadingIf(),
          ],
        ));
  }

  Widget buildLoadingIf() {
    if (busy) {
      return Positioned.fill(
        child: Container(
          width: screenSize.width,
          height: screenSize.height,
          color: Colors.black.withOpacity(0.2),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              SpinKitRing(
                color: Colors.grey,
                lineWidth: 3.0,
              ),
              Text(loadingText),
            ],
          ),
        ),
      );
    }
    return Opacity(
      opacity: 0,
    );
  }

  void downloadUser() async {
    setState(() {
      busy = true;
      loadingText = '正在下载用户信息';
    });
    var receiver = ReceivePort();
    var isolate = await Isolate.spawn(_download, receiver.sendPort);
    var dio = DioHttp.instance();
    var sqlite = SqliteHelper.instance;
    // 等待isolate发送消息并处理
    SendPort sendPort;
    receiver.listen((msg) {
      if (msg is SendPort) {
        sendPort = msg;
        sendPort.send({
          'dio': dio,
          'path': '/user/download',
        });
      } else if (msg is Result) {
        if (msg.success) {
          sqlite.delete(Tables.pda_user, 'code <> ?', ['root']);
          var batch = sqlite.batch;
          var len = msg.data.length;
          for (var item in msg.data) {
            var u = User.fromJson(item);
            batch.rawInsert(User.insertSql(), u.insertSqlArgs());
          }
          batch.commit(noResult: true).whenComplete(() {
            setState(() {
              busy = false;
            });
            showSuccess(context, '用户信息共下载: $len条.');
            isolate.kill();
          });
        } else {
          setState(() {
            busy = false;
          });
          showSuccess(context, msg.message ?? '用户信息下载失败.');
          isolate.kill();
        }
      }
    });
  }

  void downloadProduct() async {
    setState(() {
      busy = true;
      loadingText = '正在下载商品信息';
    });
//    compute(_longTimeWork, {'dio': DioHttp.instance()});
    // 创建一个新的isolate
    var receiver = ReceivePort();
    var isolate = await Isolate.spawn(_download, receiver.sendPort);
    var dio = DioHttp.instance();
    var sqlite = SqliteHelper.instance;
    // 等待isolate发送消息并处理
    SendPort sendPort;
    receiver.listen((msg) {
      if (msg is SendPort) {
        sendPort = msg;
        sendPort.send({
          'dio': dio,
          'path': '/product/download',
        });
      } else if (msg is Result) {
        if (msg.success) {
          sqlite.delete(Tables.pda_product, '1 = 1', []);
          var batch = sqlite.batch;
          var len = msg.data.length;
          for (var item in msg.data) {
            var p = Product.fromJson(item);
            batch.rawInsert(Product.insertSql(), p.insertSqlArgs());
          }
          batch.commit(noResult: true).whenComplete(() {
            setState(() {
              busy = false;
            });
            showSuccess(context, '商品信息共下载: $len条.');
            isolate.kill();
          });
        } else {
          setState(() {
            busy = false;
          });
          showSuccess(context, msg.message ?? '商品信息下载失败.');
          isolate.kill();
        }
      }
    }).onError((_) {
      debugPrint(_.toString());
      showError(context, _.toString());
      isolate.kill();
    });
  }

  void downloadProvider() async {
    setState(() {
      busy = true;
      loadingText = '正在下载供应商信息';
    });
//    compute(_longTimeWork, {'dio': DioHttp.instance()});
    // 创建一个新的isolate
    var receiver = ReceivePort();
    var isolate = await Isolate.spawn(_download, receiver.sendPort);
    var dio = DioHttp.instance();
    var sqlite = SqliteHelper.instance;
    // 等待isolate发送消息并处理
    SendPort sendPort;
    receiver.listen((msg) {
      if (msg is SendPort) {
        sendPort = msg;
        sendPort.send({
          'dio': dio,
          'path': '/provider/download',
        });
      } else if (msg is Result) {
        if (msg.success) {
          sqlite.delete(Tables.pda_provider, '1 = 1', []);
          var batch = sqlite.batch;
          var len = msg.data.length;
          for (var item in msg.data) {
            var p = Provider.fromJson(item);
            batch.rawInsert(Provider.insertSql(), p.insertSqlArgs());
          }
          batch.commit(noResult: true).whenComplete(() {
            setState(() {
              busy = false;
            });
            showSuccess(context, '供应商信息共下载: $len条.');
            isolate.kill();
          });
        } else {
          setState(() {
            busy = false;
          });
          showSuccess(context, msg.message ?? '供应商信息下载失败.');
          isolate.kill();
        }
      }
    }).onError((_) {
      debugPrint(_.toString());
      showError(context, _.toString());
      isolate.kill();
    });
  }

  void downloadDepart() async {
    setState(() {
      busy = true;
      loadingText = '正在下载部门/仓库信息';
    });
//    compute(_longTimeWork, {'dio': DioHttp.instance()});
    // 创建一个新的isolate
    var receiver = ReceivePort();
    var isolate = await Isolate.spawn(_download, receiver.sendPort);
    var dio = DioHttp.instance();
    var sqlite = SqliteHelper.instance;
    // 等待isolate发送消息并处理
    SendPort sendPort;
    receiver.listen((msg) {
      if (msg is SendPort) {
        sendPort = msg;
        sendPort.send({
          'dio': dio,
          'path': '/depart/download',
        });
      } else if (msg is Result) {
        if (msg.success) {
          sqlite.delete(Tables.pda_depart, '1 = 1', []);
          var batch = sqlite.batch;
          var len = msg.data.length;
          for (var item in msg.data) {
            var p = Depart.fromJson(item);
            batch.rawInsert(Depart.insertSql(), p.insertSqlArgs());
          }
          batch.commit(noResult: true).whenComplete(() {
            setState(() {
              busy = false;
            });
            showSuccess(context, '部门/仓库信息共下载: $len条.');
            isolate.kill();
          });
        } else {
          setState(() {
            busy = false;
          });
          showSuccess(context, msg.message ?? '部门/仓库信息下载失败.');
          isolate.kill();
        }
      }
    }).onError((_) {
      debugPrint(_.toString());
      showError(context, _.toString());
      isolate.kill();
    });
  }
}

_download(SendPort sendPort) {
  // 使用receiver接受消息
  var receiver = ReceivePort();
  // 使用sendPort与宿主isolate通讯, 将当前isolate的sendPort发送给宿主isolate，以便宿主发消息给自己
  sendPort.send(receiver.sendPort);
//  宿主isolate发送过来的消息
  receiver.listen((msg) async {
    var dio = msg['dio'];
    debugPrint('DioHttp: ${dio.hashCode}');
    var path = msg['path'];
    var i = 0;
    dio.get(path, onResult: (result) {
      sendPort.send(result);
    });
    Future.delayed(Duration(milliseconds: 500), receiver.close);
  });
}
